package com.jz.main.io.websocket;
import java.io.*;
import java.net.*;
import java.util.HashMap;

public class WebSocketServer {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("WebSocket Server started.");

        HashMap<Socket,String> map = new HashMap<>();

        while (true) {
            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected: " + clientSocket);

            new Thread(() -> {
                try {
                    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

                    String request;
                    while ((request = in.readLine()) != null) {
                        System.out.println("Received from client: " + request);
                        if(request.contains("user")){
                            map.put(clientSocket,"user");
                        }else if(request.contains("mail:")){
                            // 给其他socket发消息
                            String cont = request.replace("mail:","");
                            for (Socket socket : map.keySet()) {
                                if (!socket.equals(clientSocket)){
                                    PrintWriter other = new PrintWriter(socket.getOutputStream(), true);
                                    other.println("come from:"+clientSocket+" : "+cont);
//                                    other.close();
                                }
                            }
                        }else{
                            // Echo back to client
                            out.println("Server received: " + request);
                        }

                        if ("exit".equalsIgnoreCase(request)) {
                            break;
                        }
                    }

                    clientSocket.close();
                    System.out.println("Client disconnected.");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
